package com.ccl.myblog.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ccl.myblog.utils.AliUtils;
import com.ccl.myblog.utils.RandomUtil;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 发送验证码
 */
@Service
@Slf4j
public class SmsService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 发送手机验证码
     *
     * @param phone
     * @param msgCode 短信模板
     * @return
     */
    public boolean sendSms(String phone, String msgCode) {
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(msgCode)) return false;
        //获取验证码
        String code = RandomUtil.getSixBitRandom();
        //自定义的code值传参需要是json数据，使用fastjson =》map集合转成json数据格式
        Map<String, Object> codeMap = new HashMap<>();
        codeMap.put("code", code);
        //创建对象
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "xxxxxxxxxxxxx", "xxxxxxxxxxxxx");
        IAcsClient client = new DefaultAcsClient(profile);
        //配置参数
        SendSmsRequest request = new SendSmsRequest();
        request.setSignName(AliUtils.ALIBABA_SMS_NAME);//短信签名
        request.setTemplateCode(msgCode);
        request.setPhoneNumbers(phone);
        request.setTemplateParam(JSONObject.toJSONString(codeMap));//传入json格式的数据
        try {
            //发送
            SendSmsResponse response = client.getAcsResponse(request);
            log.info("response=={}",new Gson().toJson(response));
            //发送后把验证码存入redis，用于验证
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            //获取状态码
            String status = response.getCode();
            if ("OK".equals(status)) return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
